package cn.yuanqiao.web.controller.activiti;

import cn.yuanqiao.activiti.aspect.AddApprovalGroup;
import cn.yuanqiao.activiti.domain.*;
import cn.yuanqiao.activiti.service.IActTaskService;
import cn.yuanqiao.activiti.service.IYqdaWorkflowArchiveSaveService;
import cn.yuanqiao.activiti.util.SecurityUtil;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.page.PageDomain;
import cn.yuanqiao.common.core.page.TableDataInfo;
import cn.yuanqiao.common.core.page.TableSupport;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.github.pagehelper.Page;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 归档流程信息Controller
 * 
 * @author lyk
 * @date 2023-07-28
 */
@RestController
@RequestMapping("/activiti/workflowArchiveSave")
public class YqdaWorkflowArchiveSaveController extends BaseController
{
    @Autowired
    private IYqdaWorkflowArchiveSaveService yqdaWorkflowArchiveSaveService;

    @Autowired
    private IActTaskService actTaskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private RuntimeService runtimeService;

    /**
     * bpmn流程图片地址
     */
    @Value("${bpmn.domain}")
    public String domain;

    /**
     * 查询归档流程信息列表
     */
    @PreAuthorize("@ss.hasPermi('activiti:workflowArchiveSave:list')")
    //@GetMapping("/list")
    public TableDataInfo listOld(YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave)
    {
        startPage();
        List<YqdaWorkflowArchiveSave> list = yqdaWorkflowArchiveSaveService.selectYqdaWorkflowArchiveSaveList(yqdaWorkflowArchiveSave);
        return getDataTable(list);
    }

    //获取我的代办任务
    @GetMapping(value = "/taskList")
    public TableDataInfo getTasks(@RequestParam(value = "instanceName",required = false) String instanceName) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<ActTaskDTO> hashMaps = actTaskService.selectProcessDefinitionListByCode(pageDomain,"WS_Archive_Save",instanceName);
        return getDataTable(hashMaps);
    }

    //获取我的代办任务
    @GetMapping(value = "/taskHistoryList")
    public TableDataInfo getTaskHistoryList(@RequestParam(value = "instanceName",required = false) String instanceName) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<ActHistoryTaskDTO> hashMaps = actTaskService.selectProcessDefinitionListHistoyByCode(pageDomain,"WS_Archive_Save",instanceName);
        return getDataTable(hashMaps);
    }

    /**
     * 查询请假列表
     */
    @PreAuthorize("@ss.hasPermi('activiti:workflowArchiveSave:list')")
    @GetMapping("/list")
    public TableDataInfo list(YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave) {
        yqdaWorkflowArchiveSave.setSTATE("0");
        startPage();
        yqdaWorkflowArchiveSave.setCreateBy(SecurityUtils.getUsername());
        List<YqdaWorkflowArchiveSave> list = yqdaWorkflowArchiveSaveService.selectYqdaWorkflowArchiveSaveList(yqdaWorkflowArchiveSave);
        for(YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave1: list){
            String url = domain+"/activitiHistory/searchApprovalBpmn?instanceId="+yqdaWorkflowArchiveSave1.getInstanceId();
            yqdaWorkflowArchiveSave1.setBpmnUrl(url);
        }
        return getDataTable(list);
    }

    /**
     * 导出归档流程信息列表
     */
    @PreAuthorize("@ss.hasPermi('activiti:workflowArchiveSave:export')")
    @Log(title = "归档流程信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave)
    {
        List<YqdaWorkflowArchiveSave> list = yqdaWorkflowArchiveSaveService.selectYqdaWorkflowArchiveSaveList(yqdaWorkflowArchiveSave);
        ExcelUtil<YqdaWorkflowArchiveSave> util = new ExcelUtil<YqdaWorkflowArchiveSave>(YqdaWorkflowArchiveSave.class);
        util.exportExcel(response, list, "归档流程信息数据");
    }

    /**
     * 获取归档流程信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('activiti:workflowArchiveSave:query')")
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") String ID)
    {
        return success(yqdaWorkflowArchiveSaveService.selectYqdaWorkflowArchiveSaveByID(ID));
    }

    /**
     * 新增归档流程信息
     */
    @PreAuthorize("@ss.hasPermi('activiti:workflowArchiveSave:add')")
    @Log(title = "归档流程信息", businessType = BusinessType.INSERT)
    @PostMapping
    @AddApprovalGroup
    public R<ActivitiPackage> add(@RequestBody Map<String,Object> virables)
    {
        YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave = new YqdaWorkflowArchiveSave();
        ProcessInstance processInstance = yqdaWorkflowArchiveSaveService.insertYqdaWorkflowArchiveSave(yqdaWorkflowArchiveSave, virables);
        ActivitiPackage activitiPackage = new ActivitiPackage();
        activitiPackage.setTableName(yqdaWorkflowArchiveSave.getTableName());
        activitiPackage.setBussinessKey(yqdaWorkflowArchiveSave.getID());
        activitiPackage.setProcessInstance(processInstance);
        return R.ok(activitiPackage);
    }


    /**
     * 修改归档流程信息
     */
    @PreAuthorize("@ss.hasPermi('activiti:workflowArchiveSave:edit')")
    @Log(title = "归档流程信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave)
    {
        return toAjax(yqdaWorkflowArchiveSaveService.updateYqdaWorkflowArchiveSave(yqdaWorkflowArchiveSave));
    }

    /**
     * 删除归档流程信息
     */
    @PreAuthorize("@ss.hasPermi('activiti:workflowArchiveSave:remove')")
    @Log(title = "归档流程信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable String[] IDs)
    {
        return toAjax(yqdaWorkflowArchiveSaveService.deleteYqdaWorkflowArchiveSaveByIDs(IDs));
    }

    /**
     * 删除归档中流程档案信息(已废弃)
     */
    @Deprecated
    @PreAuthorize("@ss.hasPermi('activiti:workflowArchiveSave:remove')")
    @Log(title = "归档流程信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteArchiveById/{processId}/{archiveId}")
    public AjaxResult deleteArchiveById(@PathVariable String processId, @PathVariable String archiveId)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        List<Map<String,Object>> variable = (List<Map<String,Object>>)runtimeService.getVariable(processId, "archiveData");
        Iterator<Map<String,Object>> iterator = variable.iterator();
        while (iterator.hasNext()){
            Map<String, Object> item = iterator.next();
            String id = String.valueOf(item.get("ID"));
            if (archiveId.equals(id)){
                iterator.remove();
            }
        }
        runtimeService.setVariable(processId,"archiveData",variable);
        //runtimeService.setVariables(processId);
        return toAjax(1);
    }

    @Log(title = "归档流程信息", businessType = BusinessType.DELETE)
    @PutMapping("/setArchiveProcessStatusByArchiveId/{processId}/{archiveId}/{status}")
    public AjaxResult setArchiveProcessStatusByArchiveId(@PathVariable("processId") String processId,
                                                         @PathVariable("archiveId") String archiveId,
                                                         @PathVariable("status") String status)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        List<Map<String,Object>> variable = (List<Map<String,Object>>)runtimeService.getVariable(processId, "archiveData");
        Iterator<Map<String,Object>> iterator = variable.iterator();
        while (iterator.hasNext()){
            Map<String, Object> item = iterator.next();
            String id = String.valueOf(item.get("ID"));
            if (archiveId.equals(id)){
                //iterator.remove();
                item.put("archiveAgreeStatus",status);
            }
        }
        runtimeService.setVariable(processId,"archiveData",variable);
        //runtimeService.setVariables(processId);
        return AjaxResult.success("状态值修改成功");
    }

    @PutMapping("/changeAllArchiveState/{processId}/{status}")
    public AjaxResult changeAllArchiveState(@PathVariable("processId") String processId,
                                                         @PathVariable("status") String status)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        List<Map<String,Object>> variable = (List<Map<String,Object>>)runtimeService.getVariable(processId, "archiveData");
        Iterator<Map<String,Object>> iterator = variable.iterator();
        while (iterator.hasNext()){
            Map<String, Object> item = iterator.next();
            if (item.get("archiveAgreeStatusCanEdit")==null||"1".equals(String.valueOf(item.get("archiveAgreeStatusCanEdit")))){
                item.put("archiveAgreeStatus",status);
            }
        }
        runtimeService.setVariable(processId,"archiveData",variable);
        return AjaxResult.success("状态值修改成功");
    }

    @Log(title = "预归档流程信息", businessType = BusinessType.INSERT)
    @PostMapping("/yuguidang")
    @AddApprovalGroup
    public R<ActivitiPackage> addY(@RequestBody Map<String,Object> virables)
    {
        YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave = new YqdaWorkflowArchiveSave();
        ProcessInstance processInstance = yqdaWorkflowArchiveSaveService.insertYqdaWorkflowYArchiveSave(yqdaWorkflowArchiveSave, virables);
        ActivitiPackage activitiPackage = new ActivitiPackage();
        activitiPackage.setTableName(yqdaWorkflowArchiveSave.getTableName());
        activitiPackage.setBussinessKey(yqdaWorkflowArchiveSave.getID());
        activitiPackage.setProcessInstance(processInstance);
        return R.ok(activitiPackage);
    }

    //获取我的预归档代办任务
    @GetMapping(value = "/YtaskList")
    public TableDataInfo getYTasks(@RequestParam(value = "instanceName",required = false) String instanceName) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<ActTaskDTO> hashMaps = actTaskService.selectProcessDefinitionListByCode(pageDomain,"YArchive_Save",instanceName);
        return getDataTable(hashMaps);
    }
    //获取我的预归档代办任务
    @GetMapping(value = "/taskYHistoryList")
    public TableDataInfo getTaskYHistoryList(@RequestParam(value = "instanceName",required = false) String instanceName) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<ActHistoryTaskDTO> hashMaps = actTaskService.selectProcessDefinitionListHistoyByCode(pageDomain,"YArchive_Save",instanceName);
        return getDataTable(hashMaps);
    }

    //获取我的提交记录
    @GetMapping(value = "/taskListByStartUser")
    public TableDataInfo getTaskListByStartUser(@RequestParam(value = "instanceName",required = false) String instanceName) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<ActActivitiDTO> hashMaps = actTaskService.selectProcessDefinitionListHistoyByCodeAndStartUser(pageDomain,"WS_Archive_Save",instanceName);
        return getDataTable(hashMaps);
    }
}
